package com.kun.coupon.mq;

import com.alibaba.fastjson2.JSON;
import com.kun.api.ICouponService;
import com.kun.common.constant.ShopCode;
import com.kun.pojo.domain.TradeCoupon;
import com.kun.pojo.entity.MQEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

@Component
@Slf4j
@RocketMQMessageListener(topic = "${mq.order.topic}", consumerGroup = "${mq.order.consumer.group}",
        messageModel = MessageModel.BROADCASTING)
public class CancelMQListener implements RocketMQListener<MessageExt> {

    @Autowired
    private ICouponService couponService;

    @Override
    public void onMessage(MessageExt messageExt) {
        try {
            // 解析消息内容
            String body = new String(messageExt.getBody(), StandardCharsets.UTF_8);
            MQEntity entity = JSON.parseObject(body, MQEntity.class);
            log.info("接收到信息");
            if (entity.getCouponId() != null && couponService.findOne(entity.getCouponId()) != null) {
                // 更新优惠券信息
                couponService.lambdaUpdate().set(TradeCoupon::getUsedTime, null)
                        .set(TradeCoupon::getIsUsed, ShopCode.SHOP_COUPON_UNUSED.getCode())
                        .set(TradeCoupon::getOrderId, null).eq(TradeCoupon::getCouponId, entity.getCouponId())
                        .update();
                log.info("回退优惠券成功");
            }
        } catch (Exception e) {
            log.error("回退优惠券失败");
        }
    }
}
